package com.qt.dispatcher;

import cn.hutool.core.lang.UUID;
import com.qt.pojo.dto.ToJudgeDTO;
import com.qt.result.R;
import com.qt.utils.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author pgw
 * @version 1.0
 * @description
 * @date Create by 2023/9/27 12:22
 */
@Slf4j
@Component
public class DisPatcher {

    @Autowired
    private RestTemplate restTemplate;

    private final static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(20);

    private final static Map<String, Future> futureTaskMap = new ConcurrentHashMap<>(20);

    public void dispatch(Constants.TaskType taskType, ToJudgeDTO toJudgeDTO) {

        defaultJudge(toJudgeDTO , taskType.getPath());
    }

    public void defaultJudge(ToJudgeDTO data, String path) {
//        String code ="import java.util.Scanner;\n" +
////                "\n" +
////                "\n" +
////                "public class Main {\n" +
////                "    public static void main(String[] args) {\n" +
////                "        Scanner sc =  new Scanner(System.in);\n" +
////                "        int a = sc.nextInt();\n" +
////                "        int b = sc.nextInt();\n" +
////                "        System.out.println(\"a = \" + a);\n" +
////                "        System.out.println(\"b = \" + b);\n" +
////                "        \n" +
////                "    }\n" +
////                "}\n";
        String code = "#include<stdio.h>\n" +
                "int main(){\n" +
                "\tint a, b;\n" +
                "\tscanf(\"%d%d\" ,&a,&b );\n" +
                "\tprintf(\"%d\\n\",a);\n" +
                "\tprintf(\"%d\",b);\n" +
                "\treturn 0;\n" +
                "} ";
        data.getJudge().setCode(code);
//        Long submitId = data.getJudge().getId();
        AtomicInteger count = new AtomicInteger(0);
//        String taskKey = UUID.randomUUID().toString() + submitId;

        Runnable getResultTask = () -> {

            count.getAndIncrement();

            R result = null;
            try {
                result = restTemplate.postForObject("http://47.103.215.76:8082/run", data, R.class);
            } catch (Exception e) {
                log.error("[Self Judge] Request the judge server [" + "127.0.0.1" + "] error -------------->", e);
            } finally {
              log.info("judge result : {}" , result );
            }

        };


        getResultTask.run();
//        ScheduledFuture<?> scheduledFuture = scheduler.scheduleWithFixedDelay(getResultTask, 0, 2, TimeUnit.SECONDS);
//        futureTaskMap.put(taskKey, scheduledFuture);
    }
}
